/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db.type;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * 字节流
 * 
 * 
 */
public class BinaryType extends NullableType {
	public Class getReturnedClass() {
		return byte[].class;
	}

	protected Object toExternalFormat(byte[] bytes) {
		return bytes;
	}

	public String getName() {
		return "binary";
	}

	public boolean isEqual(Object x, Object y) {
		return x.equals(y);
	}

	public void set(PreparedStatement st, Object value, int index)
			throws SQLException {
		st.setBytes(index, (byte[]) value);
	}

	public Object get(ResultSet rs, String name) throws SQLException {
		InputStream inputStream = rs.getBinaryStream(name);
		if (inputStream == null)
			return toExternalFormat(null);

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
		byte[] buffer = new byte[2048];

		try {
			while (true) {
				int amountRead = inputStream.read(buffer);
				if (amountRead == -1) {
					break;
				}
				outputStream.write(buffer, 0, amountRead);
			}

			inputStream.close();
			outputStream.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			throw new SQLException(
					"IOException occurred reading a binary value");
		}

		return toExternalFormat(outputStream.toByteArray());

	}

	public int sqlType() {
		return Types.VARBINARY;
	}

	@Override
	public String getTypeValue(Object value) {
		// TODO Auto-generated method stub
		return String.valueOf(value);
	}

}
